package com.gzist.elderlyserviceplatform.config;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.gzist.elderlyserviceplatform.entity.po.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.List;

/**
 * 公共字段抽取
 */
@Slf4j
@Component
public class MyBatisPlusMetaObjectHandler implements MetaObjectHandler {
    private static final ZoneId ZONE_ID = ZoneId.of("Asia/Shanghai");  // 指定时区，比如中国标准时间

    private static final List<String> COMMON_FIELDS = Arrays.asList(
            "createTime", "updateTime", "createBy", "updateBy", "delFlag"
    );
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("开始插入填充...");

        // 只有在特定条件下才进行填充
        if (shouldFill(metaObject)) {
            this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now(ZONE_ID));
            this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now(ZONE_ID));
            String doUser = "";
            String delFlag = "0";
            if (!StpUtil.isLogin()) {
                // 说明此时是注册行为，需要手动修改公共字段信息
                doUser = "admin";
            }else {
                User user = (User) StpUtil.getSession().get("user");
                if (ObjectUtil.isNotEmpty(user)) {
                    doUser = user.getUsername();
                }
            }
            this.strictInsertFill(metaObject, "createBy", String.class, doUser);
            this.strictInsertFill(metaObject, "updateBy", String.class, doUser);
            this.strictInsertFill(metaObject, "delFlag", String.class, delFlag);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("开始更新填充...");

        // 只有在特定条件下才进行填充
        if (shouldFill(metaObject)) {
            this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now(ZONE_ID));

            String doUser = "";
            if (!StpUtil.isLogin()) {
                // 说明此时是重置密码或者其他行为，需要手动修改公共字段信息
                doUser = "admin";
            }else {
                User user = (User) StpUtil.getSession().get("user");
                if (ObjectUtil.isNotEmpty(user)) {
                    doUser = user.getName();
                }
            }
            this.strictUpdateFill(metaObject, "updateBy", String.class, doUser);
        }
    }

    private boolean shouldFill(MetaObject metaObject) {
        // 检查目标对象是否包含公共字段
        for (String field : COMMON_FIELDS) {
            if (metaObject.hasSetter(field)) {
                return true; // 如果包含公共字段，则返回 true 进行填充
            }
        }
        return false; // 如果不包含公共字段，则返回 false 不进行填充
    }
}
